class Solution8 {
    boolean[][] visited;
    int m;
    int n;
    char[] word;

    /**
     * [79. 单词搜索 - 力扣（LeetCode）](https://leetcode.cn/problems/word-search/description/)
     *
     * @param board
     * @param _word
     * @return
     */

    public boolean exist(char[][] board, String _word) {
        m = board.length;
        n = board[0].length;
        word = _word.toCharArray();
        visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word[0]) {
                    visited[i][j] = true;
                    if (dfs(board, i, j, 1)) {
                        return true;
                    }
                    visited[i][j] = false;
                }
            }
        }
        return false;
    }

    // 向量数组,表示i,j的上下左右四个方向
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};

    public boolean dfs(char[][] board, int i, int j, int pos) {
        if (pos == word.length) {
            return true;
        }
        //判断上下左右四个方位
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && visited[x][y] == false
                    && board[x][y] == word[pos]) {
                visited[x][y] = true;
                if (dfs(board, x, y, pos + 1)) {
                    return true;
                }
                visited[x][y] = false;
            }
        }
        return false;
    }
}